/**
 * request 网络请求工具
 * 更详细的 api 文档: https://github.com/umijs/umi-request
 */
import { extend } from 'umi-request';
import { Toast } from 'antd-mobile';
import { getToken, getTenantid, removeToken } from '@/utils/auth'
import router from 'umi/router'

// const codeMessage = {
//   400: '发出的请求有错误，服务器没有进行新建或修改数据的操作。',
//   401: '用户没有权限。',
//   999: '用户鉴权检查失败。',
// };
/**
 * 异常处理程序
 */

const errorHandler = error => {
  const { response } = error;
  if (response && response.status) {
    // const errorText = codeMessage[response.status] || response.statusText;
    const { status, url } = response;
    Toast.fail(`请求错误 ${status}: ${url}`);
  }
};
/**
 * 配置request请求时的默认参数
 */

const request = extend({
  errorHandler,
  // 默认错误处理
  // credentials: 'include', // 默认请求是否带上cookie
});
// request拦截器, 改变url 或 options.
request.interceptors.request.use((url, options) => {
  const data = Object.prototype.toString.call(options.data) === '[object FormData]'
  ? options.data
  : {...options.data };
  // eslint-disable-next-line
  options.headers = {
    ...options.headers,
    token: getToken() || '',
    tenantId: getTenantid(),
  }
  return { options: { ...options, data } };
});
// response拦截器, 处理response
request.interceptors.response.use(async response => {
  const res = await response.clone().json();
  return new Promise((resolve, reject) => {
    if (res && res.code === 200) {
      resolve(response);
    } else if(res && [401, -901,-902, -903,-910,-920,-999 ].includes(res.code)) {
      Toast.fail(res.msg)
      removeToken()
      setTimeout(() => {
        router.push(`/${getTenantid()}`)
      })
    } else {
      Toast.fail(res.msg || res.errMsg);
      reject(response);
    }
  });
}, { global: false });

export default request;
